package com.nd.mobile.study.common;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import com.nd.mobile.study.R;
import com.nd.mobile.study.common.constants.SharedPreferenceConstants;
import com.nd.mobile.study.common.util.SharedPreferencesUtil;
import com.nd.mobile.study.view.LoginActivity;
import com.nd.mobile.study.view.TabMainActivity;
import com.nd.mobile.study.view.helper.ToastHelper;
import com.nd.mobile.study.view.widget.Loading;

/**
 * 常用的界面操作汇总类
 * 
 * @author guozw
 * 
 */
public abstract class BaseActivity extends FragmentActivity {

	private static String			TAG				= "BaseActivity";

	protected boolean				isExit			= false;

	protected App				mApp;

	protected AlertDialog			shutdownDlg		= null;			// 退出

	protected AlertDialog			mLogoutDlg;						// 注销
	
	protected AlertDialog			checkLoginDlg		= null;			// 检查登录

	protected boolean				isFullScreen	= false;

	protected String				night			= null;

	protected SharedPreferencesUtil	mPreferences;

	protected AlertDialog			loadingDialog;
	
	protected Loading	mLoading;
	
	protected ImageButton mHeaderBtnBack;
	protected ImageButton mHeaderBtnInfo;
	protected Button mHeaderBtnLogin;
	protected ImageButton mHeaderBtnHome;
	protected TextView mHeaderTitleTv;

	// protected BroadcastReceiver screenReceiver = null;

	@Override
	protected void onResume() {
		super.onResume();
	};

	@Override
	protected void onPause() {
		super.onPause();
	}

	/**
	 * Activity退出的效果anim文件id
	 */
	// protected int animType= R.anim.activity_out;
	/**
	 * Activity退出效果的最顶层viewgroup的ID 也作为开启和关闭动画效果的开关----若为0则关闭效果，如果为某一个ID值则为开启效果
	 */
	protected int	layoutId	= 0;

	/**
	 * 基础构建前的动作，需要时进行重载
	 * 
	 * @param savedInstanceState
	 *            bundle
	 */
	protected void onBeforeCreate(Bundle savedInstanceState) {
	}

	/**
	 * 基础构建动作，常用于设置视图等相关动作
	 * 
	 * @param savedInstanceState
	 *            bundle
	 */
	abstract protected void onBaseCreate(Bundle savedInstanceState);

	/**
	 * 控件初始化后相关动作，可以初始化需要的Handler
	 * 
	 * @param savedInstanceStat
	 *            bundle
	 */
	abstract protected void onAfterCreate(Bundle savedInstanceStat);

	@Override
	final protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mApp = (App) BaseActivity.this.getApplication();
		mPreferences = SharedPreferencesUtil.getSyscfgSp(this);

		mApp.registActivity(this);
		mLoading = new Loading(this);
		onBeforeCreate(savedInstanceState);
		onBaseCreate(savedInstanceState);
		initViews();
		setFieldValues();
		onAfterCreate(savedInstanceState);
	}

	/**
	 * 控件初始化
	 */
	abstract protected void initViews();
	
	/**
	 * 初始化header
	 * override时先调用super.initHeader()
	 */
	protected void initHeader(){
		mHeaderBtnBack = (ImageButton)findViewById(R.id.header_btn_back);
		mHeaderBtnBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		mHeaderBtnInfo = (ImageButton)findViewById(R.id.header_btn_info);
		mHeaderBtnLogin = (Button)findViewById(R.id.header_btn_login);
		mHeaderTitleTv = (TextView) findViewById(R.id.header_title_tv);
		if(mApp.hasUserLogin() == false){
			mHeaderBtnLogin.setVisibility(View.VISIBLE);
			mHeaderBtnLogin.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					toLoginActivity();
				}
			});
		}
		mHeaderBtnHome = (ImageButton)findViewById(R.id.header_btn_home);
		mHeaderBtnHome.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(BaseActivity.this, TabMainActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				intent.putExtra("index", 2);
				finish();
				startActivity(intent);
			}
		});
	}
	
	/**
	 * 
	 * 作用:设置初始值，按需重载并调用
	 */
	protected void setFieldValues() {
	}

	/**
	 * 隐藏软键盘
	 */
	public void hideKeyboard() {
		InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		View view = getCurrentFocus();
		if (view != null) {
			imm.showSoftInput(view, 0); // 显示软键盘
			imm.hideSoftInputFromWindow(view.getWindowToken(), 0);// 隐藏软键盘
		}
	}
	
	/**
	 * 检查是否登录,未登录显示登录提示
	 */
	protected boolean checkLogin(){
		boolean checkResult = mApp.hasUserLogin();
		if(checkResult == false){
			if (null == checkLoginDlg) {
				checkLoginDlg = new AlertDialog.Builder(this).setTitle("您还没有登录,请先登录后使用此功能")
						.setPositiveButton("登录", new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog, int which) {
								toLoginActivity();
							}
						}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								checkLoginDlg.dismiss();
							}
						}).create();
			}
			checkLoginDlg.show();
		}
		return checkResult;
	}
	
	/**
	 * 跳转到登录
	 */
	protected void toLoginActivity(){
		Intent intent = new Intent(BaseActivity.this,LoginActivity.class);
		startActivity(intent);
	}

	/*
    *//**
	 * 显示等待显示框
	 * 
	 * @param title
	 *            标题
	 * @param message
	 *            内容
	 */
	/*
	 * public final void showProgress(String message) {
	 * Loading.show(this,message).show(); }
	 */

	/**
	 * 退出程序
	 */
	public final void exitProgram() {
		/*
		 * Intent intent = new Intent(); intent.setAction(Constants.PACKAGE); //
		 * 说明动作 sendBroadcast(intent);// 该函数用于发送广播
		 */// 获得SDK的版本号
			// this.unregisterReceiver(screenReceiver);
		mApp.setUser(null);
		mApp.finishActivities();
		if (Build.VERSION.SDK_INT < 8) {// 如果SDK版本号小于8，即android2.2以下的系统
			((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE)).restartPackage(getPackageName());
		} else {// 如果SDK版本号大于等于8，即android2.2以上的系统
			// 退出时记录流量信息
			Intent startMain = new Intent(Intent.ACTION_MAIN);
			startMain.addCategory(Intent.CATEGORY_HOME);
			startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(startMain);
			System.exit(0);
		}
	}

	/**
	 * 弹出退出程序的对话框
	 */
	public final void showExitDialog() {
		if (null == shutdownDlg) {
			shutdownDlg = new AlertDialog.Builder(this).setTitle("确定要退出程序吗?")
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							exitProgram();
						}
					}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							shutdownDlg.dismiss();
						}
					}).create();
		}
		shutdownDlg.show();
	}

	/**
	 * 弹出退出程序的对话框
	 */
	public final void showLogOutDialog() {
		if (null == mLogoutDlg) {
			mLogoutDlg = new AlertDialog.Builder(this).setTitle("请确认").setMessage("确定要注销吗?")
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							logout();
						}

					}).setNegativeButton("取消", null).create();
		}
		mLogoutDlg.show();
	}

	/**
	 * 注销(重启应用)
	 */
	public final void logout() {
		isExit = false;
		mApp.setUser(null);
		Intent intent = new Intent();
		// intent.setClass(BaseActivity.this, InitActivity.class);
		mPreferences.putBooleanValue(SharedPreferenceConstants.SYSCFG_IS_FROM_LOGOUT, true);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
		mApp.finishActivities();
	}

	/**
	 * 获取屏幕宽度
	 * 
	 * @return 屏幕宽度
	 */
	public final int getScreenWidth() {
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		return metrics.widthPixels;
	}

	/**
	 * 获取屏幕高度
	 * 
	 * @return 屏幕高度
	 */
	public final int getScreenHeight() {
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		return metrics.heightPixels;
	}

//	@Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		boolean flag = (keyCode == KeyEvent.KEYCODE_BACK);
//		// boolean flag = (keyCode == KeyEvent.KEYCODE_BACK &&
//		// event.getRepeatCount() == 0);
//		if (flag) {
//			showExitDialog();
//		}
//		return flag;
//	}

	public final void changeBright() {
		ToastHelper.displayToast(this, "进入系统亮度设置");
		startActivityForResult(new Intent(android.provider.Settings.ACTION_DISPLAY_SETTINGS), 0);
	}

	/*
	 * @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater
	 * inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu);
	 * return true; }
	 */

	/*
	 * @Override public boolean onPrepareOptionsMenu(Menu menu) { if
	 * (isFullScreen) {
	 * menu.findItem(R.id.item_out_fullscreen).setVisible(true);
	 * menu.findItem(R.id.item_fullscreen).setVisible(false); } else {
	 * menu.findItem(R.id.item_fullscreen).setVisible(true);
	 * menu.findItem(R.id.item_out_fullscreen).setVisible(false); }
	 * menu.findItem(R.id.item_night_mode_setting).setVisible(false);
	 * menu.findItem(R.id.item_day_mode_setting).setVisible(false); return
	 * super.onPrepareOptionsMenu(menu); }
	 */

	/**
	 * 检查更新
	 * 
	 * @param isAuto
	 */
	public final void checkUpdate(boolean isAuto) {
		// AppUpdateHelper.getInstance(this).update(isAuto);
	}

	/*
	 * @Override public boolean onOptionsItemSelected(MenuItem item) { int
	 * item_id = item.getItemId(); switch (item_id) { case
	 * R.id.item_fullscreen:// 全屏 // 记录到友盟 MobclickAgent.onEvent(this,
	 * UmengVar.ENTER_FULL_SCREEN);
	 * 
	 * switchFullScreenState(); break; case R.id.item_out_fullscreen:// 退出全屏模式
	 * // 记录到友盟 MobclickAgent.onEvent(this, UmengVar.EXIT_FULL_SCREEN);
	 * 
	 * switchFullScreenState(); break; case R.id.item_brightness:// 亮度调节 //
	 * 记录到友盟 MobclickAgent.onEvent(this, UmengVar.MENU_BRIGHTNESS_ADJUSTMENT);
	 * 
	 * changeBright(); break; case R.id.item_network_setting:// 网络设置 // 记录到友盟
	 * MobclickAgent.onEvent(this, UmengVar.SET_NETWORK);
	 * 
	 * ToastHelper.displayToast(this, "进入系统网络设置"); Intent intent = new
	 * Intent("android.settings.WIRELESS_SETTINGS");
	 * BaseActivity.this.startActivity(intent); break; case
	 * R.id.item_checkupdate:// 检查更新 // 记录到友盟 MobclickAgent.onEvent(this,
	 * UmengVar.MENU_CHECK_UPDATE);
	 * 
	 * checkUpdate(false); break; case R.id.item_about:// 关于 // 记录到友盟
	 * MobclickAgent.onEvent(this, UmengVar.MENU_ABOUT); showDownloadManager();
	 * //showAboutDialog(); break; case R.id.item_shutdown:// 退出 // 记录到友盟
	 * MobclickAgent.onEvent(this, UmengVar.MENU_EXIT_PROGRAM);
	 * 
	 * showExitDialog(); break; case R.id.item_download:// 下载管理 //TODO 下载管理引入
	 * showDownloadManager(); break;
	 * 
	 * default: break; } return super.onOptionsItemSelected(item); }
	 */

	// public final long getUserId() {
	// User user = null;
	// try {
	// user = mApp.getUser();
	// } catch (Exception e) {
	// return 0l;
	// }
	// if (null == user) {
	// finish();
	// Intent intent = new Intent(this, InitActivity.class);
	// startActivity(intent);
	// return 0l;
	// } else {
	// return user.getUserId();
	// }
	// }

	/**
	 * Header上back键的onClick回调
	 * 
	 * @param v
	 */
	public void headerBack(View v) {
		finish();
	}
	
	public Loading getLoading() {
		return mLoading;
	}
}
